var graceJS = require('../../GraceJS/grace.js');
var graceChecker = require("../../graceUI/jsTools/graceChecker.js");
var common = require('../../common.js');
const req = require('../../req/index.js');
var app = getApp();
var pageData;
const ywlx = "1";
Page({
	data: {
		top: 0,
		errorMsg: '',
		successMsg: '',
		schedules: null,
		currentDate: '',
		pageLoading: false,
		step: "1",
		check: false,
		cjh: "",
		hphm: "",
		zjhm: "",
		org: {},
		day: {},
		date: '',
		time: {},
		zjlxArr: ['居民身份证', '港澳台居民居住证', '境外人员身份证明', '外教人员身份证明', '外国人永久居留身份证', '居住暂住证明', '临时居民身份证'],
		zjlxIndex: 0,
		hpzlArr: [],
		hpzlIndex: 0,
		sfArr: ['粤', '京', '津', '沪', '渝', '冀', '豫', '云', '辽', '黑', '湘', '皖', '鲁', '新', '苏', '浙', '赣', '鄂', '桂', '甘', '晋',
			'蒙', '陕', '吉', '闽', '贵', '青', '藏', '川', '宁', '琼', '使', '领'
		],
		sfIndex: 0,
		orgArr: [],
		dayArr: [],
		timeArr: [],
		image_id: '',
		image_path: '',
		imageCode: '',
		screenHeightStep1 : '',
		screenHeightStepOther : ''
	},
	onLoad() {
		pageData = this.data;
		this.setData({
			currentDate: common.getNowFormatDate(),
			screenHeightStep1: app.globalData.proportion * wx.getSystemInfoSync().windowHeight - 260 - (app.globalData.proportion * wx.getSystemInfoSync().statusBarHeight + 44),
			screenHeightStepOther: app.globalData.proportion * wx.getSystemInfoSync().windowHeight - 170 - (app.globalData.proportion * wx.getSystemInfoSync().statusBarHeight + 44)
			// top: wx.getSystemInfoSync().statusBarHeight + 44
		})
		console.log(wx.getSystemInfoSync());
	},
	scheduleTap(e) {
		var id = e.detail;
		wx.showToast({
			title: "id " + id,
			icon: "none"
		});
	},
	chooseDate(e) {
		var day = e.detail;
		this.setData({
			date: day,
			time: {},
			timeArr: []
		})
		for (let i in pageData.dayArr) {
			if (pageData.dayArr[i].date == day) {
				this.setData({
					day: pageData.dayArr[i]
				})
			}
		}
		req.wfyy.getTimeSlots(pageData.org.id, day, ywlx)
			.then((res) => {
				if(res.head.code == 1){
					this.setData({
						timeArr: res.dataList
					})
				}else{
					this.errorShow(res.head.message);
				}
			})
			.catch(req.err.show);
	},
	gotoToday(e) {
		this.chooseDate(e);
	},
	getImageCode() {
		let randNum = common.getMathRand();
		this.setData({
			image_id: randNum,
			image_path: req.common.getImgCode(randNum)
		});
	},
	goback() {
		wx.navigateBack();
	},
	selectOrg(e) {
		var selOrg = e.currentTarget.dataset.key;
		console.log(selOrg);
		this.setData({
			org: selOrg
		});
	},
	selectDay(e) {
		var selDay = e.currentTarget.dataset.key;
		console.log(selDay);
		this.setData({
			day: selDay
		});
	},
	selectTime(e) {
		var selTime = e.currentTarget.dataset.key;
		console.log(selTime);
		this.setData({
			time: selTime
		});
	},
	successShow(msg) {
		this.setData({
			successMsg: msg
		});
		this.selectComponent('#errorMsg').close();
		this.selectComponent('#successMsg').open();
	},
	errorShow(msg) {
		this.setData({
			errorMsg: msg
		});
		this.selectComponent('#successMsg').close();
		this.selectComponent('#errorMsg').open();
	},
	stepto: function(e) {
		console.log(pageData);
		var index = e.currentTarget.dataset.step;
		switch (index) {
			case "1":
				break;
			case "2":
				if (!pageData.check) {
					this.errorShow("请阅读办理须知,并勾选");
					return;
				}
				//获取号牌种类字典
				req.wfyy.getDictionarys("HPZL")
					.then((res) => {
						if(res.head.code == 1){
							this.setData({
								hpzlArr: res.dataList
							})
						}else{
							this.errorShow(res.head.message);
						}
					})
					.catch(req.err.show);
				break;
			case "3":
				//定义数据规则
				var rule = [{
						name: "hphm",
						checkType: "reg",
						checkRule: /^[a-z0-9A-Z]{6,7}$/,
						errorMsg: "请输入正确的号牌号码"
					},
					{
						name: "cjh",
						checkType: "string",
						checkRule: "6,6",
						errorMsg: "请正确输入车架号后六位"
					},
					{
						name: "zjhm",
						checkType: "notnull",
						checkRule: "",
						errorMsg: "请输入证件号码"
					}
				];
				if (pageData.zjlxArr[pageData.zjlxIndex] == "居民身份证") {
					let jsonRule = {
						name: "zjhm",
						checkType: "reg",
						checkRule: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
						errorMsg: "证件号码格式错误"
					};
					rule.push(jsonRule);
				}
				//进行数据检查 
				var checkRes = graceChecker.check(pageData, rule);
				if (!checkRes) {
					this.errorShow(graceChecker.error);
					return;
				}

				//获取机构
				if (!this.orgArr) {
					req.wfyy.getOrgs(ywlx, '')
						.then((res) => {
							if(res.head.code == 1){
								this.setData({
									orgArr: res.dataList
								})
							}else{
								this.errorShow(res.head.message);
							}
						})
						.catch(req.err.show);
				}

				break;
			case "4":
				if (common.getJsonLength(pageData.org) == 0) {
					this.errorShow("请选择机构");
					return;
				}
				//获取可预约日期
				req.wfyy.getDates(pageData.org.id)
					.then((res) => {
						if(res.head.code == 1){
							this.setData({
								dayArr: res.dataList,
							})
							if (pageData.dayArr.length != 0) {
								let dateArr = [];
								for (let i in pageData.dayArr) {
									let checkDataJson = {};
									checkDataJson['id'] = i;
									checkDataJson['datetime'] = pageData.dayArr[i].date;
									dateArr.push(checkDataJson);
								}
								this.setData({
									schedules: dateArr,
									currentDate: pageData.dayArr[0].date
								});
								var e = {
									detail: pageData.currentDate
								};
								this.chooseDate(e);
							} else {
								this.setData({
									schedules: []
								});
							}
						}else{
							this.errorShow(res.head.message);
						}
					})
					.catch(req.err.show);
				break;
			case "5":
				if (common.getJsonLength(pageData.day) == 0) {
					this.errorShow("请选择预约日期");
					return;
				}
				if (common.getJsonLength(pageData.time) == 0) {
					this.errorShow("请选择预约时间");
					return;
				}
				let day = pageData.date;
				let chooseTrueDay = false;
				for (let i in pageData.dayArr) {
					if (pageData.dayArr[i].date == day) {
						chooseTrueDay = true;
					}
				}
				console.log("chooseTrueDay: " + chooseTrueDay);
				if (!chooseTrueDay) {
					this.errorShow("当前预约日期不在可选范围之内");
					return;
				}
				this.getImageCode();
				break;
		}
		this.setData({
			step: index
		});
	},
	// 提交
	submit: function() {
		let rule = [{
				name: "imageCode",
				checkType: "notnull",
				checkRule: "",
				errorMsg: "请输入验证码"
			},
			{
				name: "imageCode",
				checkType: "stirng",
				checkRule: "4,4",
				errorMsg: "验证码长度不正确"
			}
		];
		//进行数据检查 
		let checkRes = graceChecker.check(pageData, rule);
		if (!checkRes) {
			this.errorShow(graceChecker.error);
			return;
		}
		this.setData({
			pageLoading: true
		});
		req.wfyy.appoint(ywlx, app.globalData.userInfo.name, app.globalData.userInfo.sjhm,
				pageData.cjh, '01', pageData.time.id, pageData.image_id, app.globalData.userInfo.clientId,
				pageData.imageCode, '', pageData.hpzlArr[pageData.hpzlIndex].code,
				pageData.sfArr[pageData.sfIndex] + pageData.hphm, Number.parseInt(pageData.zjlxIndex) + 1, pageData.zjhm, pageData.cjh)
			.then((res) => {
				if(res.head.code == 1){
					wx.showModal({
						title: '预约成功',
						content: res.head.message + '\r\n 流水号 : ' + res.lsh + '\r\n 手机号码 : ' + res.sjhm,
						showCancel: false,
						success(res) {
							if (res.confirm) {
								wx.redirectTo({
									url : '../yyrecord/yyrecord'
								})
							} else if (res.cancel) {
								/* wx.switchTab({
									url: '../my/my'
								}) */
							}
						}
					})
					
				}else{
					this.errorShow(res.head.message);
				}
			})
			.catch(req.err.show)
			.then(()=>{
				this.setData({
					pageLoading: false
				});
			})
	}
});
